#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.h>
#include<string.h>
#include<assert.h>
#include<stdlib.h>
#define NUM 1024

typedef struct MyFILE_{
    int fd;
    char buffer[NUM];
    int end;//当前缓冲区的结尾
}MyFILE;

MyFILE *fopen_(const char* pathname,const char* mode)
{
    assert(pathname);
    assert(mode);
    
    MyFILE *fp=NULL;
    if(strcmp(mode,"r")==0)
    {

    }
    else if(strcmp(mode,"r+")==0)
    {

    }
    else if(strcmp(mode,"w")==0)
    {
        int fd=open(pathname,O_WRONLY|O_CREAT|O_TRUNC,0666);
        if(fd>=0)
        {
            fp=(MyFILE*)malloc(sizeof(MyFILE));
            memset(fp,0,sizeof( MyFILE));
            fp->fd=fd;
        }
    }
    
    else if(strcmp(mode,"w+")==0)
    {

    }
    else if(strcmp(mode,"a")==0)
    {

    }
    else if(strcmp(mode,"a+")==0)
    {

    }
    else 
    {

    }
    return fp;
}

void fputs_(const char* message,MyFILE* fp)
{
    assert(message);
    assert(fp);
    
    strcpy(fp->buffer+fp->end,message);
    fp->end+=strlen(message);


     //刷新策略
     if(fp->fd==0)
     {
          //标准输入
     }
     else if(fp->fd==1)
     {
          //标准输出
        if(fp->buffer[fp->end-1]=='\n')
        {
            fprintf(stderr,"fflush:%s",fp->buffer);
            write(fp->fd,fp->buffer,fp->end);
            fp->end=0;
        }
     }
     else if(fp->fd==2)
     {
          //标准错误
     }
     else 
     {
          //其他文件
     }
}

void fflush_(MyFILE* fp)
{
    assert(fp);
    if(fp->end!=0)
    {
        //暂且认为刷新了,实际上是把数据写入了内核
        write(fp->fd,fp->buffer,fp->end);
        syncfs(fp->fd);//将数据写入到磁盘
        fp->end=0;
    }
}

void fclose_(MyFILE* fp)
{
    assert(fp);
    fflush_(fp);
    close(fp->fd);
    free(fp);
}

int main()
{
    close(1);
    MyFILE* fp=fopen_("./log.txt","w");
    if(fp==NULL)
    {
        printf("open file error\n");
        return 1;
    }
    
    fputs_("ont:hello world",fp);
    fputs_("two:hello world\n",fp);
    fputs_("three:hello world",fp);
    fputs_("four:hello world\n",fp);
    fclose_(fp);
    return 0;
}



//int main()
//{
//    //C语言提供的
//    printf("hello printf\n");
//    fprintf(stdout,"hello fprintf\n");
//    const char* s="hello fputs\n";
//    fputs(s,stdout);
//
//    //OS提供的
//    const char* ss="hello write\n";
//    write(1,ss,strlen(ss));
//
//    //fork前，强制刷新
//    fflush(stdout);
//    fork();
//
//    return 0;
//}
